package com.onstar.cn.framework.network;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.SparseArray;

import com.onstar.cn.common.error.CommErrorUtils;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.framework.BuildConfig;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.entity.SSLConnectionFactory;
import com.onstar.cn.framework.network.http.ByteResponseHandler;
import com.onstar.cn.framework.network.http.CommonError;
import com.onstar.cn.framework.utils.ContextInstance;
import com.onstar.cn.framework.utils.ExceptionUtil;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.framework.utils.RxBus;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

public class BaseRequest {
    public static final int CHECK_NET_CONNECT = 1001020;
    private final int default_http_code = 505;
    private boolean isCancel = false;
    // Connection time out
    private int timeout = 15 * 1000;
    // Auto connect
    private boolean isRetryConnect = false;
    // 重试次数
    private int retryCount = 3;
    // 请求tag，区分不同Request请求
    private String tag = "";
    private Context mContext;


//    private Map<Integer, String> responseData = new HashMap<Integer, String>(1);
//    private Map<Integer, Object> responseObject = new HashMap<Integer, Object>(1);

    private SparseArray<String> responseData = new SparseArray(1);
    private SparseArray<Object> responseObject = new SparseArray(1);

    private RequestEntity requestEntity;

    private ByteResponseHandler responseHandler;

    public boolean isCancel() {
        return isCancel;
    }

    public void setCancel(boolean isCancel) {
        this.isCancel = isCancel;
    }

    public BaseRequest(RequestEntity requestEntity, ByteResponseHandler responseHandler) {
        this.requestEntity = requestEntity;
        this.responseHandler = responseHandler;
    }

    public BaseRequest(RequestEntity requestEntity) {
        this.requestEntity = requestEntity;
    }

    public BaseRequest(RequestEntity requestEntity, Context context) {
        this.requestEntity = requestEntity;
        this.mContext = context;
    }

    private LogManager log = LogManager.getInstance();

    private void setReport(long startimeStamp, long endStartimeStamp, String errValue, String url) {
        if (requestEntity != null && requestEntity.report != null) {
//            String json = JsonUtils.object2Json(requestEntity.report);
//            LogManager.getInstance(mContext).d("setReport..start..:" + json);
            Method[] methods = requestEntity.report.getClass().getDeclaredMethods();// 获得类的方法集合
            for (Method method : methods) {
//                LogManager.getInstance(mContext).d("setReport method:" + method.getName());
                if (method.getName().equals("setTraceID")) {
                    try {
                        LogManager.getInstance(mContext).d("setReport....ex: setTraceID");
                        method.invoke(requestEntity.report, ClientTraceInstance.getInstance().getClientTraceId());
                        continue;
                    } catch (Exception ex) {
                    }
                }
                if (method.getName().equals("getEvent")) {
                    try {
                        Object event = method.invoke(requestEntity.report);
                        Method[] eventMethods = event.getClass().getDeclaredMethods();// 获得类的方法集合
                        for (Method eventMethod : eventMethods) {
//                            LogManager.getInstance(mContext).d("setReport eventMethods:" + method.getName());
                            if (eventMethod.getName().equals("setStartTimestamp")) {
                                eventMethod.invoke(event, startimeStamp);
                                continue;
                            }
                            if (eventMethod.getName().equals("setEndTimestamp")) {
                                eventMethod.invoke(event, endStartimeStamp);
                                continue;
                            }
                            if (eventMethod.getName().equals("setType")) {
                                eventMethod.invoke(event, "3");
                                continue;
                            }
                            if (eventMethod.getName().equals("setObjectType")) {
                                eventMethod.invoke(event, "3");
                                continue;
                            }
                            if (eventMethod.getName().equals("setObjectID")) {
                                eventMethod.invoke(event, url);
                                continue;
                            }
                            if (eventMethod.getName().equals("setResult")) {
                                eventMethod.invoke(event, TextUtils.isEmpty(errValue) ? "0" : "1");
                                continue;
                            }
                            if (!CommonUtil.isNull(errValue) && eventMethod.getName().equals("getExtra")) {
                                List<Object> extraList = (List<Object>) eventMethod.invoke(event);
                                for (Object extra : extraList) {
                                    Field extraField = extra.getClass().getDeclaredField("code");// 获得类的方法集合
                                    if (extraField.get(extra).equals("error")) {
                                        LogManager.getInstance(mContext).d("setReport....error:" + errValue);
                                        extra.getClass().getDeclaredMethod("setValue").invoke(extra, errValue);
                                        break;
                                    }
                                }
                                continue;
                            }
                        }
                    } catch (Exception ex) {
                        log.e(ex.getMessage());
                    }
                }
            }
            try {
                if (requestEntity.reportSender != null) {
                    Method method = ((Class) requestEntity.reportSender).getDeclaredMethod("sendReport", requestEntity.report.getClass());
                    method.invoke(null, requestEntity.report);
                }
            } catch (Exception ex) {
//                LogManager.getInstance(mContext).d("setReport..send..ex:" + ex.getMessage() + ";" + ex.getCause().getMessage());
            }
        }
//        String json = JsonUtils.object2Json(requestEntity.report);
//        LogManager.getInstance(mContext).d("setReport..end..:" + json);

    }

    /**
     * 执行网络请求
     *
     * @return
     */
    public SparseArray<String> excute() {
        Long startTimeStamp = System.currentTimeMillis();
        String errValue = "";
        String response = "";
        int code = 200;
        try {
            URL requestUrl = new URL(requestEntity.getUrl());
            HttpURLConnection conn = null;
            if (requestEntity.getUrl().contains("https")) {
                //忽略证书信任
//				SSLContext sc = SSLContext.getInstance("TLS");
//				sc.init(null, new TrustManager[] { new MytmArray() }, new SecureRandom());
//				HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//				HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
//                conn = (HttpsURLConnection) requestUrl.openConnection();
//                conn.setRequestMethod(requestEntity.getMethod());

//                SSLContext sslcontext = SSLContext.getInstance("TLSv1");
//                sslcontext.init(null, null, null);
//                SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
//                HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
//                conn = (HttpsURLConnection) requestUrl.openConnection();
//                conn.setRequestMethod(requestEntity.getMethod());
//                conn = SSLConnectionFactory.createCommonSSLConnection(requestEntity);
                conn = SSLConnectionFactory.createStrictSSLConnection(ContextInstance.getInstance().getAppContext(),requestEntity);
//                conn = SSLConnectionFactory.createCommonSSLConnection(requestEntity);
            } else {
                conn = (HttpURLConnection) requestUrl.openConnection();
                conn.setRequestMethod(requestEntity.getMethod());
            }
            conn.setConnectTimeout(timeout > 0 ? timeout : 15 * 1000);
            conn.setReadTimeout(timeout > 0 ? timeout : 15 * 1000);

//			if (!CommonUtil.isNull(requestEntity.getAccept())) {
            conn.addRequestProperty("Accept", requestEntity.getAccept());
//			}

            if (!CommonUtil.isNull(requestEntity.getAccept())) {
                conn.addRequestProperty("Content-Type", requestEntity.getAccept() + ";charset=utf-8");
            }
            if (!CommonUtil.isNull(requestEntity.getLanguage())) {
                conn.addRequestProperty("Accept-Language", requestEntity.getLanguage());
            }
            conn.addRequestProperty(Constants.CLIENT_TRACE_ID, ClientTraceInstance.getInstance().getClientTraceId());

            /**
             * 需要统一加入head的client-info
             */
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("ANDROID");
            stringBuilder.append("_");
            stringBuilder.append(Build.VERSION.RELEASE);
            stringBuilder.append("_");
            stringBuilder.append(BuildConfig.VERSION_CODE);
            stringBuilder.append("_");
            if (DeviceUtil.getLanguage() != null && DeviceUtil.getCountry() != null) {
                stringBuilder.append(DeviceUtil.getLanguage() + "-" + DeviceUtil.getCountry().toUpperCase());
            } else {
                stringBuilder.append("zh-CN");
            }
            stringBuilder.append("_");
            stringBuilder.append(DeviceUtil.getDeviceType());
            stringBuilder.append("_");
            stringBuilder.append(Constants.CLIENT_INFO_SECRET_ID);
            log.d("client info ------------>" + stringBuilder.toString());
            conn.addRequestProperty("CLIENT-INFO", stringBuilder.toString());

            if (!CommonUtil.isNull(requestEntity.getCustomHeads())) {
                Set<Map.Entry<String, Object>> set = requestEntity.getCustomHeads().entrySet();
                Iterator<Map.Entry<String, Object>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    if (!CommonUtil.isNull(conn.getRequestProperty(entry.getKey()))) {
                        conn.setRequestProperty(entry.getKey(), entry.getValue() + "");
                    } else {
                        conn.addRequestProperty(entry.getKey(), entry.getValue() + "");
                    }
                }
            }
            log.d(requestEntity.getUrl() == null ? "url is null" : requestEntity.getUrl());
            if (!CommonUtil.isNull(requestEntity.getUrl()) && (requestEntity.getUrl().contains("mag") || requestEntity.getUrl().contains("msp"))) {
                //需要设置Default Authorization，否则接口无法调用
                conn.addRequestProperty("Authorization", !CommonUtil.isNull(requestEntity.getAuthorization()) ? requestEntity.getAuthorization() : "Authorization");
            } else {
                if (!CommonUtil.isNull(requestEntity.getAuthorization())) {
                    conn.addRequestProperty("Authorization", requestEntity.getAuthorization());
                }
            }
            log.d(getInterfaceName() + ",request Header------------>" + conn.getRequestProperties() == null ? "" : conn.getRequestProperties().toString());
            if (!CommonUtil.isNull(requestEntity.getBody())) {
                conn.setDoOutput(true);
                OutputStream output = conn.getOutputStream();
                log.d(getInterfaceName() + ",request body------------>" + requestEntity.getBody());
                output.write(requestEntity.getBody().getBytes());
                output.close();
            }
//            if (responseHandler != null) {
            // 202 NA doc
            if (conn.getResponseCode() != 200 && conn.getResponseCode() != 202) {
                InputStream is = conn.getErrorStream();
                String encodingHeader = conn.getHeaderField("Content-Encoding");
                if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip")) {
                    is = new GZIPInputStream(is);
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line = null;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                errValue = response;
                log.e(getInterfaceName() + ",failure response ------------>" + sb + conn.getResponseCode());
                CommErrorUtils entity = CommErrorUtils.parseResponse(sb.toString());
//                    responseHandler.onError(tag, new HttpException(entity.getErrorCode(), entity.getErrorMsg()),
//                            isCancel);
                if (entity != null) {
                    response = exceptionToResponse(new HttpException(entity.getErrorCode(), entity.getErrorMsg()));
                } else {
                    response = exceptionToResponse(ExceptionUtil.toHttpException(new NullPointerException()));
                }
                br.close();
                is.close();
                conn.disconnect();
            } else {
                InputStream is = conn.getInputStream();
                String encodingHeader = conn.getHeaderField("Content-Encoding");
                if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip")) {


                    is = new GZIPInputStream(is);
                }
                if (requestEntity.isByteResponse()) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    response = outputStream.toByteArray().toString();
                    log.e("success response ------------>" + outputStream.toByteArray().toString());
                    outputStream.close();
                    is.close();
                } else {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line = null;
                    StringBuilder sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    log.i(getInterfaceName() + ",success response ------------>" + sb);
//                    responseHandler.onSuccess(tag, sb.toString(), isCancel);
                    response = sb.toString();
                    br.close();
                    is.close();
                }
                conn.disconnect();
            }
            code = conn.getResponseCode();
//            }
            conn.disconnect();
        } catch (java.net.SocketTimeoutException e) {
            log.e(e.getMessage());
            errValue = e.getMessage();
            if (responseHandler != null) {
                responseHandler.onError(tag, ExceptionUtil.toHttpException(e));
            }
            code = default_http_code;
            response = exceptionToResponse(ExceptionUtil.toHttpException(e));
        } catch (MalformedURLException e) {
            errValue = e.getMessage();
            log.e(e.getMessage());
            if (responseHandler != null) {
                responseHandler.onError(tag, ExceptionUtil.toHttpException(e));
            }
            code = default_http_code;
            response = exceptionToResponse(ExceptionUtil.toHttpException(e));
        } catch (IOException e1) {
            errValue = e1.getMessage();
            log.e(e1.getMessage());
            if (isRetryConnect) {
                excute();
                retryCount--;
                if (retryCount <= 1) {
                    isRetryConnect = false;
                    retryCount = 3;
                }
            } else {
//                if (responseHandler != null) {
//                }
                code = default_http_code;
                if (!CommonUtil.isNull(e1.getMessage()) && e1.getMessage().contains("No authentication")) {
                    CommonError error = new CommonError();
//                        OnStarException e;
                    if (getInterfaceName().equals("upgrade")) {
                        error.setErrorCode("L7_invalid_user_credentials_number_dummy");
                        error.setErrorMessage("L7_invalid_user_credentials_number_dummy");
//                            e=new OnStarException("L7_invalid_user_credentials_number_dummy","L7_invalid_user_credentials_number_dummy");
                    } else {
//                            e=new OnStarException("L7_invalid_user_credentials_dummy","L7_invalid_user_credentials_dummy");
                        error.setErrorCode("L7_invalid_user_credentials_dummy");
                        error.setErrorMessage("L7_invalid_user_credentials_dummy");
                    }
                    response = GsonHelper.toJson(error);
//                        responseHandler.onError(tag, ExceptionUtil.toOnStarException(e.getErrorCode(), e.getMessage()), isCancel);
                } else {
                    response = exceptionToResponse(ExceptionUtil.toHttpException(e1));
//                        responseHandler.onError(tag, ExceptionUtil.toHttpException(e1), isCancel);
                }
            }
        } catch (Exception e) {
            errValue = e.getMessage();
            log.e(e.getMessage());
            if (isRetryConnect) {
                excute();
                retryCount--;
                if (retryCount <= 1) {
                    isRetryConnect = false;
                    retryCount = 3;
                }
            } else {
//                if (responseHandler != null) {
////                    responseHandler.onError(tag, ExceptionUtil.toHttpException(e), isCancel);
//                }
                code = default_http_code;
                response = exceptionToResponse(ExceptionUtil.toHttpException(e));
            }
        } finally {
            if (!(code == 200 || code == 202)) {
                RxBus.getDefault().post(CHECK_NET_CONNECT, "checkNet");
            }
            long endTimeStamp = System.currentTimeMillis();
            setReport(startTimeStamp, endTimeStamp, errValue, requestEntity.getUrl());
        }
        responseData.put(code, response);
        return responseData;
    }


    /**
     * 执行网络请求
     *
     * @return
     */
    public SparseArray<Object> excuteByObject() {
        Object response = "";
        int code = 200;
        try {
            URL requestUrl = new URL(requestEntity.getUrl());
            HttpURLConnection conn = null;
            if (requestEntity.getUrl().contains("https")) {
                //忽略证书信任
//                SSLContext sc = SSLContext.getInstance("TLS");
//                sc.init(null, new TrustManager[]{new MytmArray()}, new SecureRandom());
//                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//                HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
//                conn = (HttpsURLConnection) requestUrl.openConnection();
//                conn.setRequestMethod(requestEntity.getMethod());

//                SSLContext sslcontext = SSLContext.getInstance("TLSv1");
//                sslcontext.init(null, null, null);
//                SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
//                HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
//                conn = (HttpsURLConnection) requestUrl.openConnection();
//                conn.setRequestMethod(requestEntity.getMethod());

                conn = SSLConnectionFactory.createStrictSSLConnection(ContextInstance.getInstance().getAppContext(),requestEntity);
//                conn = SSLConnectionFactory.createCommonSSLConnection(requestEntity);
            } else {
                conn = (HttpURLConnection) requestUrl.openConnection();
                conn.setRequestMethod(requestEntity.getMethod());
            }
            conn.setConnectTimeout(timeout > 0 ? timeout : 15 * 1000);
            conn.setReadTimeout(timeout > 0 ? timeout : 15 * 1000);

//			if (!CommonUtil.isNull(requestEntity.getAccept())) {
            conn.addRequestProperty("Accept", requestEntity.getAccept());
//			}

            if (!CommonUtil.isNull(requestEntity.getAccept())) {
                conn.addRequestProperty("Content-Type", requestEntity.getAccept() + ";charset=utf-8");
            }
            if (!CommonUtil.isNull(requestEntity.getLanguage())) {
                conn.addRequestProperty("Accept-Language", requestEntity.getLanguage());
            }
            conn.addRequestProperty(Constants.CLIENT_TRACE_ID, ClientTraceInstance.getInstance().getClientTraceId());

            /**
             * 需要统一加入head的client-info
             */
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("ANDROID");
            stringBuilder.append("_");
            stringBuilder.append(Build.VERSION.RELEASE);
            stringBuilder.append("_");
            stringBuilder.append(BuildConfig.VERSION_CODE);
            stringBuilder.append("_");
            if (DeviceUtil.getLanguage() != null && DeviceUtil.getCountry() != null) {
                stringBuilder.append(DeviceUtil.getLanguage() + "-" + DeviceUtil.getCountry().toUpperCase());
            } else {
                stringBuilder.append("zh-CN");
            }
            stringBuilder.append("_");
            stringBuilder.append(DeviceUtil.getDeviceType());
            stringBuilder.append("_");
            stringBuilder.append(Constants.CLIENT_INFO_SECRET_ID);
            log.d("client info ------------>" + stringBuilder.toString());
            conn.addRequestProperty("CLIENT-INFO", stringBuilder.toString());


            if (!CommonUtil.isNull(requestEntity.getCustomHeads())) {
                Set<Map.Entry<String, Object>> set = requestEntity.getCustomHeads().entrySet();
                Iterator<Map.Entry<String, Object>> it = set.iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    if (!CommonUtil.isNull(conn.getRequestProperty(entry.getKey()))) {
                        conn.setRequestProperty(entry.getKey(), entry.getValue() + "");
                    } else {
                        conn.addRequestProperty(entry.getKey(), entry.getValue() + "");
                    }
                }
            }
            if (!CommonUtil.isNull(requestEntity.getUrl()) && (requestEntity.getUrl().contains("mag") || requestEntity.getUrl().contains("msp"))) {
                //需要设置Default Authorization，否则接口无法调用
                conn.addRequestProperty("Authorization", !CommonUtil.isNull(requestEntity.getAuthorization()) ? requestEntity.getAuthorization() : "Authorization");
            } else {
                if (!CommonUtil.isNull(requestEntity.getAuthorization())) {
                    conn.addRequestProperty("Authorization", requestEntity.getAuthorization());
                }
            }

            if (!CommonUtil.isNull(requestEntity.getBody())) {
                conn.setDoOutput(true);
                OutputStream output = conn.getOutputStream();
                log.d(getInterfaceName() + ",request body------------>" + requestEntity.getBody());
                output.write(requestEntity.getBody().getBytes());
                output.close();
            }
//            if (responseHandler != null) {
            // 202 NA doc
            if (conn.getResponseCode() != 200 && conn.getResponseCode() != 202) {
                InputStream is = conn.getErrorStream();
                String encodingHeader = conn.getHeaderField("Content-Encoding");
                if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip")) {
                    is = new GZIPInputStream(is);
                }
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line = null;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                log.i(getInterfaceName() + ",failure response ------------>" + sb + conn.getResponseCode());
                CommErrorUtils entity = CommErrorUtils.parseResponse(sb.toString());
//                    responseHandler.onError(tag, new HttpException(entity.getErrorCode(), entity.getErrorMsg()),
//                            isCancel);
                if (entity != null) {
                    response = exceptionToResponse(new HttpException(entity.getErrorCode(), entity.getErrorMsg()));
                } else {
                    response = exceptionToResponse(new HttpException("", ""));
                }
                br.close();
                is.close();
                conn.disconnect();
            } else {
                InputStream is = conn.getInputStream();
                String encodingHeader = conn.getHeaderField("Content-Encoding");
                if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip")) {
                    is = new GZIPInputStream(is);
                }
                if (requestEntity.isByteResponse()) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    response = outputStream.toByteArray();
                    log.i(getInterfaceName() + ",success response ------------>" + outputStream.toByteArray().toString());
                    outputStream.close();
                    is.close();
                } else {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String line = null;
                    StringBuilder sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    log.i(getInterfaceName() + ",success response ------------>" + sb);
//                    responseHandler.onSuccess(tag, sb.toString(), isCancel);
                    response = sb.toString();
                    br.close();
                    is.close();
                }
                conn.disconnect();
            }
            code = conn.getResponseCode();
//            }
            conn.disconnect();
        } catch (java.net.SocketTimeoutException e) {
            log.e(e.getMessage());
            if (responseHandler != null) {
                responseHandler.onError(tag, ExceptionUtil.toHttpException(e));
            }
            code = default_http_code;
            response = exceptionToResponse(ExceptionUtil.toHttpException(e));
        } catch (MalformedURLException e) {
            log.e(e.getMessage());
            if (responseHandler != null) {
                responseHandler.onError(tag, ExceptionUtil.toHttpException(e));
            }
            code = default_http_code;
            response = exceptionToResponse(ExceptionUtil.toHttpException(e));
        } catch (IOException e1) {
            log.e(e1.getMessage());
            if (isRetryConnect) {
                excute();
                retryCount--;
                if (retryCount <= 1) {
                    isRetryConnect = false;
                    retryCount = 3;
                }
            } else {
//                if (responseHandler != null) {
//                }
                code = default_http_code;
                if (!CommonUtil.isNull(e1.getMessage()) && e1.getMessage().contains("No authentication")) {
                    CommonError error = new CommonError();
//                        OnStarException e;
                    if (getInterfaceName().equals("upgrade")) {
                        error.setErrorCode("L7_invalid_user_credentials_number_dummy");
                        error.setErrorMessage("L7_invalid_user_credentials_number_dummy");
//                            e=new OnStarException("L7_invalid_user_credentials_number_dummy","L7_invalid_user_credentials_number_dummy");
                    } else {
//                            e=new OnStarException("L7_invalid_user_credentials_dummy","L7_invalid_user_credentials_dummy");
                        error.setErrorCode("L7_invalid_user_credentials_dummy");
                        error.setErrorMessage("L7_invalid_user_credentials_dummy");
                    }
                    response = GsonHelper.toJson(error);
//                        responseHandler.onError(tag, ExceptionUtil.toOnStarException(e.getErrorCode(), e.getMessage()), isCancel);
                } else {
                    response = exceptionToResponse(ExceptionUtil.toHttpException(e1));
//                        responseHandler.onError(tag, ExceptionUtil.toHttpException(e1), isCancel);
                }
            }
        } catch (Exception e) {
            log.e(e.getMessage());
            if (isRetryConnect) {
                excute();
                retryCount--;
                if (retryCount <= 1) {
                    isRetryConnect = false;
                    retryCount = 3;
                }
            } else {
//                if (responseHandler != null) {
////                    responseHandler.onError(tag, ExceptionUtil.toHttpException(e), isCancel);
//                }
                code = default_http_code;
                response = exceptionToResponse(ExceptionUtil.toHttpException(e));
            }
        } finally {
            if (!(code == 200 || code == 202)) {
                RxBus.getDefault().post(CHECK_NET_CONNECT, "checkNet");
            }
        }
        responseObject.put(code, response);
        return responseObject;
    }

    public String getInterfaceName() {
        String name = "";
        if (!CommonUtil.isNull(requestEntity) && !CommonUtil.isNull(requestEntity.getUrl())) {
            if (requestEntity.getUrl().contains("/") && requestEntity.getUrl().contains("?")) {
                name = requestEntity.getUrl().substring(requestEntity.getUrl().lastIndexOf("/") + 1, requestEntity.getUrl().indexOf("?"));
            } else if (requestEntity.getUrl().contains("/") && !requestEntity.getUrl().contains("?")) {
                name = requestEntity.getUrl().substring(requestEntity.getUrl().lastIndexOf("/") + 1, requestEntity.getUrl().length());
            } else {
                name = "";
            }
        }
        log.d("interface name:" + name);
        return name;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public boolean isRetryConnect() {
        return isRetryConnect;
    }

    public void setRetryConnect(boolean isRetryConnect) {
        this.isRetryConnect = isRetryConnect;
    }

    public int getRetryCount() {
        return retryCount;
    }

    public void setRetryCount(int retryCount) {
        this.retryCount = retryCount;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String exceptionToResponse(HttpException httpException) {
        CommonError error = new CommonError();
        error.setErrorCode(httpException.getErrorCode());
        error.setErrorMessage(httpException.getMessage());
        return GsonHelper.toJson(error);
    }

//    /**
//     * 信任所有主机-对于任何证书都不做检查
//     *
//     * @author 7828wc
//     */
//    class MytmArray implements X509TrustManager {
//        public X509Certificate[] getAcceptedIssuers() {
//            // return null;
//            return new X509Certificate[]{};
//        }
//
//        @Override
//        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//
//        }
//
//        @Override
//        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//        }
//    }
//
//    ;

//    private class MyHostnameVerifier implements HostnameVerifier {
//
//        @Override
//        public boolean verify(String hostname, SSLSession session) {
//            return true;
//        }
//    }
//
//    private HttpsURLConnection generateCertFileWhenHttps(String mUrl, Context mContext) {
//        try {
//            CertificateFactory cf = CertificateFactory.getInstance("X.509");
//            // uwca.crt 打包在 asset 中，该证书可以从https://itconnect.uw.edu/security/securing-computer/install/safari-os-x/下载
//            InputStream caInput = new BufferedInputStream(mContext.getAssets().open("uwca.crt"));
//            Certificate ca;
//            try {
//                ca = cf.generateCertificate(caInput);
//            } finally {
//                caInput.close();
//            }
//
//            // Create a KeyStore containing our trusted CAs
//            String keyStoreType = KeyStore.getDefaultType();
//            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
//            keyStore.load(null, null);
//            keyStore.setCertificateEntry("ca", ca);
//
//            // Create a TrustManager that trusts the CAs in our KeyStore
//            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
//            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
//            tmf.init(keyStore);
//
//            // Create an SSLContext that uses our TrustManager
//            SSLContext context = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");
//            context.init(null, tmf.getTrustManagers(), null);
//
//            URL url = new URL("https://certs.cac.washington.edu/CAtest/");
//            HttpsURLConnection urlConnection =
//                    (HttpsURLConnection) url.openConnection();
//            urlConnection.setSSLSocketFactory(context.getSocketFactory());
//            return urlConnection;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
}
